package org.qiyu.live.im.core.server.handler.Impl;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.qiyu.live.im.constants.ImMsgCodeEnum;
import org.qiyu.live.im.core.server.common.ChannelHandlerContextCache;
import org.qiyu.live.im.core.server.common.ImContextAttr;
import org.qiyu.live.im.core.server.common.ImContextUtils;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.core.server.handler.SimplyHandler;
import org.qiyu.live.im.core.server.interfaces.constants.ImCoreServicerConstants;
import org.qiyu.live.im.dto.ImMsgBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Description: 登出消息处理
 * @Author: 张广焱
 * @Date: 2023-12-03 13:15
 */
@Component
public class LogoutMsgHandler implements SimplyHandler {
    private static final Logger logger = LoggerFactory.getLogger(LogoutMsgHandler.class);
@Resource
private StringRedisTemplate stringRedisTemplate;
    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg imMsg) {
        Long userId = ImContextUtils.getUserId(ctx);
        Integer appId = ImContextUtils.getAppId(ctx);
        if (userId == null) {
            logger.error("attr error,imMsg is {}", imMsg);
            //有可能是错误的消息包导致，直接放弃连接
            throw new IllegalArgumentException("attr is error");
        }
        //将im消息回写到客户端
        ImMsgBody imMsgBody = new ImMsgBody();
        imMsgBody.setUserId(userId);
        imMsgBody.setAppId(appId);
        imMsgBody.setData("true");
        ImMsg respMsg = ImMsg.build(ImMsgCodeEnum.IM_LOGOUT_MSG.getCode(), JSON.toJSONString(imMsgBody));
        ctx.writeAndFlush(respMsg);
        logger.error("logoutMsgHandler login success,userid is {},appid is {}", userId, appId);
        //理想情况下 用户端断线的时候 回发送一个断线的消息包
        ChannelHandlerContextCache.remove(userId);
        stringRedisTemplate.delete(ImCoreServicerConstants.IM_BIND_IP_KEY+userId+appId);
        ImContextUtils.removeUserId(ctx);
        ImContextUtils.removeAppId(ctx);
        //连接关闭
        ctx.close();
    }
}
